import axios from "axios"; // 引用axios
import config from "./config.js";
import Encryption from '../util/encryption.js'
import { ElLoading,ElMessage,ElMessageBox } from 'element-plus'
/**请求失败后的错误统一处理 */


// key for des
const desKey = config.key();

const instance = axios.create({
  baseURL: config.baseUrl.yxy,
  timeout: 60000,
  withCredentials:true,
  headers: { "x-requested-with": "XMLHttpRequest"
  ,"From-Time":"true","agent":"zGvX6EpN$8kR#Bo5tzN78&t5JoXlxn8K"
  ,"Content-Type":"application/json;charset=UTF-8"
  }
});

function redirectLoginPage(message){
	      ElMessageBox.alert(message, '会话失效', {
	        confirmButtonText: 'OK',
	        callback: (action) => {
		
			let theme =	localStorage.getItem("theme");
			let href =  theme==null || theme == 'yxy'?'/#/login':'/' + theme + '/#/login'
			 window.location.href = href +  '?t=' + new Date().getTime();;
	        },
	      })
		  for (let i = 1; i < 100; i++) {
		    clearInterval(i);
		  }
}

function TransferString(content)
{
    var string = content;
    try{
        string=string.replace(/\r\n/g,"")
        string=string.replace(/\n/g,"");
    }catch(e) {
      console.error(e)
    }
    return string;
}

instance.interceptors.response.use(
 // 请求成功
    res => {
			if(res.status === 200){
				if(res.data != null && res.data.length > 0){
					  // console.log(res.data);
					let decryptData = Encryption.DESDecrypt(TransferString(res.data),desKey);
					if(decryptData != null && decryptData.length > 0){
						//console.log(decryptData);
						res.data = JSON.parse(decryptData);
					}else{
						res.data = null;
					}

				}

				return Promise.resolve(res);
			}else{
				ElMessage({
							showClose: true,
							message: res.data.message,
							type: 'error',
						  })
				return Promise.reject(res.data);
			}
	},
    // 请求失败
    error => {
        const { response } = error;
        if (response) {
           // 状态码判断
           switch (response.status) {
				// 401: 未登录状态，跳转登录页
				case 401:
				redirectLoginPage();
           		break;
               // 403 token过期
               // 清除token并跳转登录页
               case 403:
                   break;
               // 404请求不存在
               case 404:
                   break;
			   // 302请求不存在
			   case 302:
			/* 	if(response.headers['location'].indexOf('/cbgzs/web') >= 0){
					redirectLoginPage();
				} */

				   break;
               default:
                 //  console.log(other);
               }


			   	let decryptData = Encryption.DESDecrypt(response.data,desKey);
				 decryptData = JSON.parse(decryptData)
			   ElMessage({
			   			showClose: true,
			   			message: `Oops,${decryptData.msg}`,
			   			type: 'error',
			   		  })
            return Promise.reject(decryptData);
        } else {
			//redirectLoginPage();
            // 处理断网的情况
            // eg:请求超时或断网时，更新state的network状态
            // network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
            // 关于断网组件中的刷新重新获取数据，会在断网组件中说明
            // store.commit('changeNetwork', false);
		 	ElMessage({
						showClose: true,
						message: 'Oops, 请检查网络.',
						type: 'error',
					  })
        }
    });

//get请求
function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params: params,
      })
      .then((response) => {
        resolve(response);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

function uidHeader(){
	let b64uid = localStorage.getItem('uuu');
	if(b64uid != null && b64uid.length >0){
		//let uid = atob(b64uid)
		instance.defaults.headers.common['uuu'] = b64uid;
	}
	var token = localStorage.getItem("token");
	instance.defaults.headers.common['token'] = token;
}
//post请求
function post(url, data = {}) {
  uidHeader();
  return new Promise((resolve, reject) => {

	let jsonData = JSON.stringify(data);
	//console.log(jsonData)
	let encrypptData = Encryption.DESEncrypt(jsonData,desKey);

    instance.post(url, {param:encrypptData}).then(
      (response) => {
        resolve(response!=undefined?response.data:{});
      },
      (err) => {
        reject(err);
      }
    );
  });
}

//post请求
function postWithOutEnc(url, data = {}) {
  return new Promise((resolve, reject) => {
	//let jsonData = JSON.stringify(data);
	//console.log(jsonData)
	//let encrypptData = Encryption.DESEncrypt(jsonData,desKey);
    instance.post(url, data).then(
      (response) => {
        resolve(response!=undefined?response:{});
      },
      (err) => {
        reject(err);
      }
    );
  });
}

const qs = require('qs');
//post请求
function postForm(url, data = {}) {
  return new Promise((resolve, reject) => {
	  let jsonData = JSON.stringify(data);
	 // console.log(jsonData)
	let encrypptData = Encryption.DESEncrypt(jsonData,desKey);
    instance.post(url, qs.stringify({param:encrypptData})).then(
      (response) => {
        resolve(response!=undefined?response.data:{});
      },
      (err) => {
        reject(err);
      }
    );
  });
}

//post请求
function postFormWitoutEnc(url, data = {}) {
  return new Promise((resolve, reject) => {
    instance.post(url, qs.stringify(data)).then(
      (response) => {
        resolve(response!=undefined?response.data:{});
      },
      (err) => {
        reject(err);
      }
    );
  });
}


export default{
	getBargainPage(form){
			return post("/roleDataHistory/bargain/page",form)
	},
	lookBargain(form){
			return post("/roleDataHistory/bargain/lookOver",form)
	},
	bargainMonitor(form){
			return post("/roleDataHistory/bargain/monitor",form)
	},
	bargainMonitorPage(form){
			return post("/roleDataHistory/bargain/monitor/page",form)
	},
	bargainMonitorRemove(form){
			return post("/roleDataHistory/bargain/monitor/remove",form)
	},
	bargainMonitorEdit(form){
			return post("/roleDataHistory/bargain/monitor/edit",form)
	},
	
	messagesAll(form){
			return post("/monitorNotification/all",form)
	},
	queryByLink(form){
			return post("/roleDataHistory/queryByLink",form)
	},
}
